﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcAtletIS.Models;

namespace MvcAtletIS.Areas.Admin.Controllers
{
    [Authorize(Roles = "Administrators")]
    public class PerformancesController : Controller
    {
        private atletisEntities db = new atletisEntities();

        //
        // GET: /Admin/Performances/

        public ViewResult Index(int CompetitionId, int? DisciplineListId)
        {
            Session["CompetitionId"] = CompetitionId;
            
            DateTime today = DateTime.Now.Date;
            var competitions = db.Competitions.Where(c => c.DateFrom < today).ToList();
            var disciplineList = db.DisciplineList
                .Where(dl => dl.CompetitionId == CompetitionId & dl.ParentId == 0 & dl.Active == true)
                .ToList();

            if (DisciplineListId == null && disciplineList != null & disciplineList.Count > 0)
            {
                DisciplineListId = disciplineList[0].ID;
            }

            ViewBag.Competition = db.Competitions.Single(c => c.ID == CompetitionId);
            ViewBag.DisciplineListId = new SelectList(disciplineList, "ID", "Name", DisciplineListId);

            var model = db.Performances
                .Include("Competitors")
                .Include("Countries")
                .Include("DisciplineList")
                .Where(p => p.DisciplineListId == DisciplineListId)
                .OrderBy(p => p.CountryId)
                .ThenBy(p => p.Club)
                .ThenBy(p => p.Surname)
                .ThenBy(p =>p.FirstName)
                .ToList();

            return View(model);
        }

        //
        // GET: /Admin/Performances/Details/5

        public ActionResult Details(int id)
        {
            Performances performances = db.Performances.SingleOrDefault(p => p.ID == id);

            if (performances == null)
            {
                return HttpNotFound();
            }

            return View(performances);
        }

        // GET: /Signups/
        public ActionResult Create(int? CompetitionId)
        {
            DateTime today = DateTime.Now;
            var disciplineList = db.DisciplineList
                .Where(dl => dl.CompetitionId == CompetitionId & dl.ParentId == 0)
                .OrderBy(dl => dl.ExternalId)
                .ToList();
            var countries = db.Countries.OrderBy(c => c.Name).ToList();

            ViewBag.DisciplineListId = new SelectList(disciplineList, "ID", "Name");
            ViewBag.CountryId = new SelectList(countries, "ID", "Name", "SVK");

            Performances model = new Performances();
            model.SB = 0;
            model.PB = 0;
            model.StartNumber = 0;

            return View(model);
        }

        [HttpPost]
        public ActionResult Create(Performances model)
        {
            model.CompetitorId = 0;

            if (String.IsNullOrEmpty(model.Club))
            {
                model.Club = string.Empty;
            }
            
            model.Lane = 0;
            model.Code = 0;
            
            model.Result = 0;
            model.AdvResult = 0;
            model.Rank = 0;
            model.SecondaryRank = 0;

            model.Reaction = string.Empty;
            model.SMS = string.Empty;
            model.Points = 0;

            model.Sync = true;
            model.Active = true;
            model.WebId = 0;
            model.ResultQuality = string.Empty;
            model.Modified = DateTime.Now;

            ModelState.Clear();
            TryValidateModel(model);

            if (model.DisciplineListId == 0)
            {
                ModelState.AddModelError("DisciplineListId", "Vyberte disciplínu, prosím.");
            }

            if (ModelState.IsValid)
            {
                db.Performances.AddObject(model);
                db.SaveChanges();

                return RedirectToAction("Index", new { CompetitionId = Session["CompetitionId"], DisciplineListId = model.DisciplineListId });
            }

            int competitionId = (int)Session["CompetitionId"];
            var disciplineList = db.DisciplineList
                .Where(dl => dl.CompetitionId == competitionId & dl.ParentId == 0)
                .ToList();
            var countries = db.Countries.OrderBy(c => c.Name).ToList();

            ViewBag.DisciplineListId = new SelectList(disciplineList, "ID", "Name", model.DisciplineListId);
            ViewBag.CountryId = new SelectList(countries, "ID", "Name", "SVK");

            return View(model);
        }

        //
        // GET: /Admin/Performances/Create
        [Authorize]
        public ActionResult CreateReg(int CompetitionId = 0, int DisciplineListId = 0, string status = "")
        {
            if (!User.IsInRole("Administrators"))
            {
                return RedirectToAction("Error", "Home", new { area = "", title = "Stránka je prístupná len pre administrátor." });
            }

            string id = User.Identity.Name;

            var competitions = db.Competitions.ToList();
            var disciplineList = db.DisciplineList.Where(dl => dl.CompetitionId == CompetitionId).ToList();
            
            var clubs = db.Clubs.Where(c => c.Active == true).OrderBy(c => c.City).ToList();
            var competitors = db.Competitors.Where(c => c.ClubId == id & c.Active == true & c.Competitor == true).OrderBy(c => c.Surname).ToList();
                        
            ViewBag.CompetitionId = new SelectList(competitions, "ID", "Name", CompetitionId);
            ViewBag.DisciplineListId = new SelectList(disciplineList, "ID", "Name", DisciplineListId);

            ViewBag.ClubId = new SelectList(clubs, "ID", "Name");
            ViewBag.CompetitorId = new SelectList(competitors, "ID", "FullName");
            ViewBag.Status = status;

            return View();
        }

        //
        // GET: /Admin/Performances/Create
        [HttpPost]
        public ActionResult CreateReg(string ClubId, Performances model, int CompetitionId = 0, int DisciplineListId = 0)
        {
            // Competitor data, SB
            if (model.CompetitorId != null)
            {
                var competitor = db.Competitors.SingleOrDefault(c => c.ID == model.CompetitorId);
                model.FirstName = competitor.Firstname;
                model.Surname = competitor.Surname;
                model.Birthdate = competitor.Birthdate;
                model.Club = competitor.Clubs.Name;
                model.CountryId = competitor.CountryId;

                var modelDisciplineList = db.DisciplineList.Single(dl => dl.ID == model.DisciplineListId);
                model.SB = 0;   // nacitat SB zo statistiky
            }

            model.StartNumber = 0;
            model.Lane = 0;
            model.Code = 0;
            model.Result = 0;
            model.AdvResult = 0;
            model.SecondaryRank = 0;
            model.Reaction = string.Empty;
            model.SMS = string.Empty;
            model.Points = 0;
            model.Sync = true;
            model.Rank = 0;

            ModelState.Clear();
            TryValidateModel(model);

            if (ModelState.IsValid)
            {
                db.Performances.AddObject(model);
                db.SaveChanges();

                model = new Performances();

                ViewBag.Status = "Vaše prihlásenie bolo úspešné.";
            }
            else
            {
                ViewBag.Status = "Prihlásenie nebolo úspešné.";
            }

            var competitions = db.Competitions.ToList();
            var disciplineList = db.DisciplineList.Where(dl => dl.CompetitionId == CompetitionId).ToList();

            var clubs = db.Clubs.Where(c => c.Active == true).OrderBy(c => c.City).ToList();
            var competitors = db.Competitors.Where(c => c.ClubId == ClubId & c.Active == true & c.Competitor == true).OrderBy(c => c.Surname).ToList();

            ViewBag.CompetitionId = new SelectList(competitions, "ID", "Name", CompetitionId);
            ViewBag.DisciplineListId = new SelectList(disciplineList, "ID", "Name", DisciplineListId);

            ViewBag.ClubId = new SelectList(clubs, "ID", "Name", ClubId);
            ViewBag.CompetitorId = new SelectList(competitors, "ID", "FullName");
            

            return View(model);
        }
        
        // GET: /Admin/Performances/Edit/5
        public ActionResult Edit(int id)
        {
            Performances performances = db.Performances.Single(p => p.ID == id);
            ViewBag.CountryId = new SelectList(db.Countries, "ID", "Name", performances.CountryId);
            return View(performances);
        }

        // POST: /Admin/Performances/Edit/5
        [HttpPost]
        public ActionResult Edit(Performances model)
        {
            if (String.IsNullOrEmpty(model.Club))
            {
                model.Club = string.Empty;
            }
            
            if (String.IsNullOrEmpty(model.Reaction))
            {
                model.Reaction = string.Empty;
            }

            if (String.IsNullOrEmpty(model.SMS))
            {
                model.SMS = string.Empty;
            }

            if (String.IsNullOrEmpty(model.ResultQuality))
            {
                model.ResultQuality = string.Empty;
            }
            
            model.Modified = DateTime.Now;
            
            if (ModelState.IsValid)
            {
                db.Performances.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();

                return RedirectToAction("Index", new { CompetitionId = model.DisciplineList.CompetitionId, DisciplineListId = model.DisciplineListId });
            }

            model.DisciplineList = db.DisciplineList.SingleOrDefault(dl => dl.ID == model.DisciplineListId);
            ViewBag.CountryId = new SelectList(db.Countries, "ID", "Name", model.CountryId);

            return View(model);
        }

        // GET: /Admin/Performances/Delete/5
        public ActionResult Delete(int id)
        {
            Performances performances = db.Performances.Single(p => p.ID == id);
            return View(performances);
        }

        //
        // POST: /Admin/Performances/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {            
            Performances performances = db.Performances.Single(p => p.ID == id);
            
            int competitionId = Convert.ToInt32(performances.DisciplineList.CompetitionId);
            int disciplineListId = Convert.ToInt32(performances.DisciplineListId);

            db.Performances.DeleteObject(performances);
            db.SaveChanges();
            return RedirectToAction("Index", new { CompetitionId = competitionId, DisciplineListId = disciplineListId });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        #region CascadeDropDown - Discipline List

        private IList<DisciplineList> GetDisciplineList(int id)
        {
            return db.DisciplineList.Where(dl => dl.CompetitionId == id & dl.ParentId == 0).OrderBy(dl => dl.ExternalId).ToList();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadDisciplinesForCompetition(string id)
        {
            var disciplineList = this.GetDisciplineList(Convert.ToInt32(id));

            var disciplineData = disciplineList.Select(m => new SelectListItem()
            {
                Text = m.Name,
                Value = m.ID.ToString(),

            });

            return Json(disciplineData, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region CascadeDropDown - Competitors

        private IList<Competitors> GetCompetitors(string id)
        {
            return db.Competitors.Where(c => c.ClubId == id & c.Competitor == true).OrderBy(c => c.Surname).ThenBy(c => c.Firstname).ToList();
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult LoadCompetitorsForClub(string id)
        {
            var competitorsList = this.GetCompetitors(id);

            var competitorsData = competitorsList.Select(m => new SelectListItem()
            {
                Text = m.FullName,
                Value = m.ID.ToString(),

            });

            return Json(competitorsData, JsonRequestBehavior.AllowGet);
        }

        #endregion





    }
}